import { app, ipcMain } from 'electron'
import ElectronStore from 'electron-store'
const Store = (ElectronStore as any).default || ElectronStore

const store = new Store({
  name: 'tasks',
  cwd: app.getPath('userData')
})
// console.log('数据存储路径', app.getPath('userData'))

// ipcMain 注册持久化 API
export default function registerTaskStoreIpc() {
  ipcMain.handle('tasks-get', () => store.get('tasks', []))
  // 新增
  ipcMain.handle('tasks-add', (_, task) => {
    const tasks = store.get('tasks', []) as any[]
    const newTask = {
      id: Date.now().toString(),
      ...task
    }
    store.set('tasks', [newTask, ...tasks])
    return newTask
  })
  // 更新
  ipcMain.handle('tasks-update', (_, task) => {
    const tasks = (store.get('tasks', []) as any[]).map((t) =>
      t.id === task.id ? { ...t, ...task } : t
    )
    store.set('tasks', tasks)
    return task
  })
  // 删除
  ipcMain.handle('tasks-delete', (_, id) => {
    const tasks = (store.get('tasks', []) as any[]).filter((t) => t.id !== id)
    store.set('tasks', tasks)
    return id
  })
}
